<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="物料编码" prop="matCode">
              <el-input v-model="queryParams.matCode" placeholder="请输入物料编码" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="物料描述" prop="matName">
              <el-input v-model="queryParams.matName" placeholder="请输入物料描述" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="物料分类" prop="matClass">
              <el-select v-model="queryParams.matClass" placeholder="请选择物料分类" clearable filterable>
                <el-option
                  v-for="item in matClassList"
                  :key="item.classCode"
                  :label="item.className"
                  :value="item.classCode"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="物料组" prop="matGroup">
              <el-select v-model="queryParams.matGroup" placeholder="请选择物料组" clearable filterable>
                <el-option
                  v-for="item in matGroupList"
                  :key="item.groupCode"
                  :label="item.groupName"
                  :value="item.groupCode"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="批次" prop="batch">
              <el-input v-model="queryParams.batch" placeholder="请输入批次" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="供应商" prop="supplierCode">
              <el-select v-model="queryParams.supplierCode" placeholder="请选择供应商" clearable filterable>
                <el-option
                  v-for="item in supplierList"
                  :key="item.supplierCode"
                  :label="item.supplierName"
                  :value="item.supplierCode"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="入库单号" prop="orderNo">
              <el-input v-model="queryParams.orderNo" placeholder="请输入入库单号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="生产时间" prop="prodTime">
              <el-date-picker clearable
                              v-model="queryParams.prodTime"
                              type="date"
                              value-format="YYYY-MM-DD"
                              placeholder="请选择生产时间"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['stock:matLabel:add']">新增</el-button>
          </el-col>
<!--          <el-col :span="1.5">-->
<!--            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['stock:matLabel:edit']">修改</el-button>-->
<!--          </el-col>-->
          <el-col :span="1.5">
            <el-button type="success" plain icon="Printer" :disabled="multiple" @click="handlePrintBatch()" v-hasPermi="['stock:matLabel:print']">批量打印</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['stock:matLabel:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['stock:matLabel:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="matLabelList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键" align="center" prop="labelId" v-if="false" />
        <el-table-column label="物料编码" fixed align="center" prop="matCode" :show-overflow-tooltip="true" min-width="100"/>
        <el-table-column label="物料描述" fixed align="center" prop="matName" :show-overflow-tooltip="true" width="120"/>
<!--        <el-table-column label="仓库" align="center" prop="warehouseCode" :show-overflow-tooltip="true" width="80"/>-->
<!--        <el-table-column label="货位" align="center" prop="locationCode" :show-overflow-tooltip="true" width="80"/>-->
<!--        <el-table-column label="标签类型" align="center" prop="labelType" :show-overflow-tooltip="true" width="120"/>-->
        <el-table-column label="财务编码" align="center" prop="fdCode" :show-overflow-tooltip="true" width="120"/>
        <el-table-column label="图号" align="center" prop="figNum" :show-overflow-tooltip="true" width="120"/>
        <el-table-column label="物料组" align="center" prop="matGroup" :show-overflow-tooltip="true" width="120"/>
        <el-table-column label="分类" align="center" prop="matClass" :show-overflow-tooltip="true" width="120"/>
        <el-table-column label="基本单位" align="center" prop="unitCode" :show-overflow-tooltip="true" width="120"/>
        <el-table-column label="批次" align="center" prop="batch" :show-overflow-tooltip="true" width="180"/>
        <el-table-column label="供应商编码" align="center" prop="supplierCode" :show-overflow-tooltip="true" width="120"/>
        <el-table-column label="供应商名称" align="center" prop="supplierName" :show-overflow-tooltip="true" width="150"/>
        <el-table-column label="生产时间" align="center" prop="prodTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.prodTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="数量" align="center" prop="quantity" />
        <el-table-column label="可用数量" align="center" prop="usableQuantity" />
        <el-table-column label="已领取数量" align="center" prop="receivedQuantity" width="120"/>
        <el-table-column label="单价" align="center" prop="unitPrice" />
        <el-table-column label="入库单号" align="center" prop="orderNo" :show-overflow-tooltip="true" width="150"/>
<!--        <el-table-column label="入库单类型" align="center" prop="orderType" :show-overflow-tooltip="true" width="120"/>-->
        <el-table-column label="操作" fixed="right"  align="center" class-name="small-padding fixed-width" width="120">
          <template #default="scope">
            <el-tooltip content="打印" placement="top">
              <el-button link type="primary" icon="Printer" @click="handlePrint(scope.row)" v-hasPermi="['stock:matLabel:print']"></el-button>
            </el-tooltip>
<!--            <el-tooltip content="修改" placement="top">-->
<!--              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['stock:matLabel:edit']"></el-button>-->
<!--            </el-tooltip>-->
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['stock:matLabel:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改物料标签对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="1000px" append-to-body>
      <el-form ref="matLabelFormRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="物料编码" prop="matCode">
              <el-input v-model="form.matCode" placeholder="请输入物料编码" readonly>
                <template #append>
                  <el-button icon="Search" @click="openSelectMatCode" />
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料描述" prop="matName">
              <el-input disabled v-model="form.matName" placeholder="请输入物料描述" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="财务编码" prop="fdCode">
              <el-input disabled v-model="form.fdCode" placeholder="请输入财务编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="图号" prop="figNum">
              <el-input disabled v-model="form.figNum" placeholder="请输入图号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="物料组" prop="fdCode">
              <el-input disabled v-model="form.fdCode" placeholder="请选择选择物料组" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类" prop="figNum">
              <el-input disabled v-model="form.figNum" placeholder="请选择分类" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="基本单位" prop="unitCode">
              <el-input disabled v-model="form.unitCode" placeholder="请输入基本单位" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="批次" prop="batch">
              <el-input v-model="form.batch" placeholder="请输入批次" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="供应商编码" prop="supplierName">
              <el-input v-model="form.supplierName" placeholder="请输入供应商编码" readonly >
                <template #append>
                  <el-button icon="Search" @click="openSelectSupplier" />
                </template>
              </el-input>
            </el-form-item>
        </el-col>
          <el-col :span="12">
            <el-form-item label="单价" prop="unitPrice">
              <el-input-number v-model="form.unitPrice" controls-position="right" :min="0" style="width: 100%;" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="数量" prop="quantity">
              <el-input-number v-model="form.quantity" controls-position="right" :min="1" style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
                <el-form-item label="生产时间" prop="prodTime">
            <el-date-picker clearable
                            v-model="form.prodTime"
                            type="date"
                            value-format="YYYY-MM-DD"
                            placeholder="请选择生产时间">
            </el-date-picker>
          </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :title="selectMatOpenDialog.title"  v-model="selectMatOpenDialog.visible" width="1300px" append-to-body :close-on-click-modal="false">
      <SelectMat @confirmSelect="confirmSelectMat"/>
    </el-dialog>

    <el-dialog :title="selectSupplierOpenDialog.title"  v-model="selectSupplierOpenDialog.visible" width="1300px" append-to-body :close-on-click-modal="false">
     <SelectSupplier @confirmSelectSupplier="confirmSelectSupplier" />
    </el-dialog>
  </div>
</template>

<script setup name="MatLabel" lang="ts">
import {
  listMatLabel,
  getMatLabel,
  delMatLabel,
  addMatLabel,
  updateMatLabel,
  printMatLabel, printMatLabelBatch
} from '@/api/wmscloud/matLabel';
import { MatLabelVO, MatLabelQuery, MatLabelForm } from '@/api/wmscloud/matLabel/types';
import { parseTime } from '@/utils/ruoyi';
import { MatGroupVO } from '@/api/wmscloud/matGroup/types';
import { MatClassVO } from '@/api/wmscloud/matClass/types';
import { SupplierVO } from '@/api/wmscloud/supplier/types';
import { listAllGroup } from '@/api/wmscloud/matGroup';
import { listAllClass } from '@/api/wmscloud/matClass';
import { listAllSupplier } from '@/api/wmscloud/supplier';
import moment from 'moment'; // 导入moment库

import SelectMat from '@/views/wmscloud/components/SelectMat/index.vue';
import SelectSupplier from '@/views/wmscloud/components/SelectSupplier/index.vue';
import { MatVO } from '@/api/wmscloud/mat/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const matLabelList = ref<MatLabelVO[]>([]);
const matGroupList = ref<MatGroupVO[]>([]);
const matClassList = ref<MatClassVO[]>([]);
const supplierList = ref<SupplierVO[]>([]);

const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const matLabelFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const selectMatOpenDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const selectSupplierOpenDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: MatLabelForm = {
  warehouseCode: undefined,
  locationCode: undefined,
  labelType: undefined,
  matCode: undefined,
  matName: undefined,
  fdCode: undefined,
  figNum: undefined,
  matGroup: undefined,
  matClass: undefined,
  unitCode: undefined,
  batch: undefined,
  supplierCode: undefined,
  supplierName: undefined,
  prodTime: undefined,
  quantity: 1,
  usableQuantity: undefined,
  receivedQuantity: undefined,
  unitPrice: 0,
  orderNo: undefined,
  orderType: undefined,
}
const data = reactive<PageData<MatLabelForm, MatLabelQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    warehouseCode: undefined,
    locationCode: undefined,
    matCode: undefined,
    matName: undefined,
    figNum: undefined,
    fdCode: undefined,
    matGroup: undefined,
    matClass: undefined,
    batch: undefined,
    supplierCode: undefined,
    supplierName: undefined,
    prodTime: undefined,
    orderNo: undefined,
    params: {
    }
  },
  rules: {
    matCode: [
      { required: true, message: "请选择物料", trigger: "blur" },
    ],
    matName: [
      { required: true, message: "物料描述不能为空", trigger: "blur" },
    ],
    fdCode: [
      { required: true, message: "财务编码不能为空", trigger: "blur" },
    ],
    figNum: [
      { required: true, message: "图号不能为空", trigger: "blur" },
    ],
    matGroup: [
      { required: true, message: "请选择物料组", trigger: "blur" },
    ],
    matClass: [
      { required: true, message: "请选择物料分类", trigger: "blur" },
    ],
    unitCode: [
      { required: true, message: "请选择基本单位", trigger: "blur" },
    ],
    batch: [
      { required: true, message: "批次不能为空", trigger: "blur" },
    ],
    supplierCode: [
      { required: true, message: "请选择供应商", trigger: "blur" },
    ],
    supplierName: [
      { required: true, message: "供应商名称不能为空", trigger: "blur" },
    ],
    prodTime: [
      { required: true, message: "请选择生产时间", trigger: "blur" },
    ],
    quantity: [
      { required: true, message: "请输入数量", trigger: "blur" },
    ],
    unitPrice: [
      { required: true, message: "请输入单价", trigger: "blur" },
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 加载所有物料组 */
const listAllGroups = async () => {
  const res = await listAllGroup();
  matGroupList.value = res.data;
}
/** 加载所有物料分类 */
const listAllClasss = async () => {
  const res = await listAllClass();
  matClassList.value = res.data;
}

/** 加载所有供应商 */
const listAllSuppliers= async () => {
  const res = await listAllSupplier();
  supplierList.value = res.data;
}

/** 查询物料标签列表 */
const getList = async () => {
  loading.value = true;
  const res = await listMatLabel(queryParams.value);
  matLabelList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  matLabelFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: MatLabelVO[]) => {
  ids.value = selection.map(item => item.labelId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加物料标签";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: MatLabelVO) => {
  reset();
  const _labelId = row?.labelId || ids.value[0]
  const res = await getMatLabel(_labelId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改物料标签";
}

/** 提交按钮 */
const submitForm = () => {
  matLabelFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.labelId) {
        await updateMatLabel(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addMatLabel(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: MatLabelVO) => {
  const _labelIds = row?.labelId || ids.value;
  await proxy?.$modal.confirm('是否确认删除物料标签编号为"' + _labelIds + '"的数据项？').finally(() => loading.value = false);
  await delMatLabel(_labelIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('wmsCloud/matLabel/export', {
    ...queryParams.value
  }, `matLabel_${new Date().getTime()}.xlsx`)
}
/** 选择物料按钮操作 */
const openSelectMatCode = () => {
  selectMatOpenDialog.visible = true;
  selectMatOpenDialog.title = "选择物料";
}
/** 选择物料子组件回调 */
const confirmSelectMat = (item: MatVO) => {
  form.value.matCode = item.matCode;
  form.value.matName = item.matName;
  form.value.fdCode = item.fdCode;
  form.value.figNum = item.figNum;
  form.value.matGroup = item.matGroup;
  form.value.matClass = item.matClass;
  form.value.batch = 'CG' + moment().format('YYYYMMDDHHmmss');
  form.value.unitCode = item.unitCode;
  cancelSelectMat();
}
/** 关闭选择物料按钮操作 */
const cancelSelectMat = () => {
  selectMatOpenDialog.visible = false;
  selectMatOpenDialog.title = "";
}
/** 选择供应商按钮操作 */
const openSelectSupplier = () => {
  selectSupplierOpenDialog.visible = true;
  selectSupplierOpenDialog.title = "选择供应商";
}
/** 选择供应商子组件回调 */
const confirmSelectSupplier = (item: SupplierVO) => {
  form.value.supplierCode = item.supplierCode;
  form.value.supplierName = item.supplierName;
  cancelSelectSupplier();
}
/** 关闭选择供应商按钮操作 */
const cancelSelectSupplier = () => {
  selectSupplierOpenDialog.visible = false;
  selectSupplierOpenDialog.title = "";
}

/** 打印按钮 */
const handlePrint = async (row?: MatLabelVO) => {
  printMatLabel(row?.labelId)
    .then((response) => {
      const binaryData = [];
      binaryData.push(response);
      const pdfUrl = window.URL.createObjectURL(new Blob(binaryData, { type: 'application/pdf' }));
      window.open(pdfUrl);
    })
    .catch((error) => {
      proxy?.$modal.msgSuccess('打印失败');
      // 处理错误，例如显示错误消息
      console.error('打印仓库信息失败:', error);
    });
}
/** 批量打印按钮 */
const handlePrintBatch = async (row?: MatLabelVO) => {
  const _labelIds = row?.labelId || ids.value;
  console.log('labelIds:', _labelIds);
  try {
    const response = await printMatLabelBatch(_labelIds);
    const binaryData = [];
    binaryData.push(response);
    const pdfUrl = window.URL.createObjectURL(new Blob(binaryData, { type: "application/pdf" }));
    window.open(pdfUrl);
  } catch (error) {
    console.error('Error during batch print:', error);
  }
};
onMounted(() => {
  getList();
  listAllGroups();
  listAllClasss();
  listAllSuppliers();
});
</script>
